package com.kanshu.client.widget.dialog;

import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.os.Message;
import androidx.annotation.NonNull;
import androidx.appcompat.widget.AppCompatButton;
import androidx.appcompat.widget.AppCompatTextView;

import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.view.Window;
import android.view.WindowManager;
import android.widget.RelativeLayout;

import com.kanshu.client.R;
import com.kanshu.client.util.DeviceUtils;


/**
 * @author yuquanmao
 * @since 2017-07-29 15:25:21
 */

public class DownTimerDialog extends Dialog implements Handler.Callback {


    private static final String TAG = "DownTimerDialog";

    //默认的总倒计时时长
    private static final long DEFAUL_MILLIS_INFUTURE = 10000L;
    //默认的时间间隔
    private static final long DEFAULT_COUNT_DOWN_INTERVAL = 1000L;
    //默认的标题
    private static final String DEFAULT_TITLE_TEXT = "提示";

    //倒计时显示
    private AppCompatTextView tvTimer;

    //计时器
    private DialogTimer mDownTimer;

    //倒计时总时长（毫秒）
    private long millisInFuture;

    //倒计时时间间隔（毫秒）
    private long countDownInterval;

    //倒计时监听
    private OnDownTimerListener mOnDownTimeListener;


    private Handler mHandler = new Handler(this);


    DownTimerDialog(@NonNull Context context) {
        super(context, R.style.Dialog);
    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        tvTimer = findViewById(R.id.tv_timer);
    }

    @Override
    protected void onStart() {
        super.onStart();
        mHandler.sendEmptyMessageDelayed(1, 1000);
    }

    @Override
    protected void onStop() {
        super.onStop();
        if (mDownTimer != null) mDownTimer.cancel();
    }


    @Override
    public boolean handleMessage(Message msg) {
        switch (msg.what) {
            case 1://开始倒计时
                if (millisInFuture <= 0L) throw new RuntimeException("没有为对话框设置倒计时时长！");
                if (countDownInterval <= 0L) countDownInterval = DEFAULT_COUNT_DOWN_INTERVAL;
                mDownTimer = new DialogTimer(millisInFuture, countDownInterval);
                mDownTimer.start();
                break;
            case 2://倒计时中
                //剩余时间
                long millisUntilFinished = (Long) msg.obj;
                if (mOnDownTimeListener != null) {
                    mOnDownTimeListener.onDowningTimer(this, millisUntilFinished);
                }
                tvTimer.setText(String.valueOf(millisUntilFinished / countDownInterval));
                break;
            case 3://倒计时结束
                if (mOnDownTimeListener != null) {
                    mOnDownTimeListener.onDownTimerFinished(this);
                }
                break;
        }
        return true;
    }

    /**
     * 设置倒计时总时长
     *
     * @param millisInFuture 倒计时总时长(second)
     */
    void setMillisInFuture(long millisInFuture) {
        this.millisInFuture = millisInFuture;
    }

    /**
     * 设置倒计时的时间间隔
     *
     * @param countDownInterval 倒计时的时间间隔(second)
     */
    void setCountDownInterval(long countDownInterval) {
        this.countDownInterval = countDownInterval;
    }

    /**
     * 倒计时监听
     *
     * @param downingTimeListener 倒计时监听接口
     */
    void setOnDownTimerListener(OnDownTimerListener downingTimeListener) {
        this.mOnDownTimeListener = downingTimeListener;
    }


    public static class Builder {

        private Context context;
        //标题
        private String title;

        //信息
        private String message;

        //确认按钮文本
        private String positiveText;

        //否认按钮文本
        private String negativeText;

        //倒计时监听
        private OnDownTimerListener mOnDownTimerListener;

        //按钮点击时间监听
        private OnClickListener mButtonClickListener;

        private long millisInFuture;

        private long countDownInterval;


        public Builder(Context context) {
            this.context = context;
        }

        public Builder setTitle(String title) {
            this.title = title;
            return this;
        }

        public Builder setMessage(String message) {
            this.message = message;
            return this;
        }

        public Builder setPositiveText(String positiveText) {
            this.positiveText = positiveText;
            return this;
        }

        public Builder setNegativeText(String negativeText) {
            this.negativeText = negativeText;
            return this;
        }


        public Builder setMillisInFuture(long millisInFuture) {
            this.millisInFuture = millisInFuture;
            return this;
        }

        public Builder setCountDownInterval(long countDownInterval) {
            this.countDownInterval = countDownInterval;
            return this;
        }

        public Builder setOnDownTimerListener(OnDownTimerListener onDownTimeListener) {
            this.mOnDownTimerListener = onDownTimeListener;
            return this;
        }

        public Builder setOnButtonClickListener(OnClickListener onClickListener) {
            this.mButtonClickListener = onClickListener;
            return this;
        }

        public DownTimerDialog create() {
            //UI
            LayoutInflater inflater = LayoutInflater.from(context);
            View layout = inflater.inflate(R.layout.dialog_down_timer_with_button, null);
            final DownTimerDialog dialog = new DownTimerDialog(context);
            dialog.setContentView(layout, new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));

            //设置对话框的尺寸
            Window window = dialog.getWindow();
            if (window != null) {
                WindowManager.LayoutParams lp = window.getAttributes();
                int[] screenSize = DeviceUtils.getScreenSizePixels(context);
                lp.width = (int) (screenSize[0] * 0.6);
                lp.height = (int) (screenSize[0] * 0.4);
                window.setAttributes(lp);
            }
            //其他属性
            dialog.setCancelable(false);
            dialog.setMillisInFuture(millisInFuture);
            dialog.setCountDownInterval(countDownInterval);
            dialog.setOnDownTimerListener(mOnDownTimerListener);

            //初始化UI控件
            AppCompatTextView tvTitle = dialog.findViewById(R.id.tv_title);
            /* AppCompatTextView tvTimer = (AppCompatTextView) dialog.findViewById(R.id.tv_timer); */
            AppCompatTextView tvMessage = dialog.findViewById(R.id.tv_message);
            RelativeLayout rltBtnContainer = dialog.findViewById(R.id.rlt_btnContainer);
            AppCompatButton btnPositive = dialog.findViewById(R.id.btn_positive);
            AppCompatButton btnNegative = dialog.findViewById(R.id.btn_negative);


            title = TextUtils.isEmpty(title) ? DEFAULT_TITLE_TEXT : title;
            tvTitle.setText(title);
            tvMessage.setText(message);

            if (TextUtils.isEmpty(positiveText) && TextUtils.isEmpty(negativeText)) {
                rltBtnContainer.setVisibility(View.GONE);
            } else {

                if (TextUtils.isEmpty(positiveText)) {
                    btnPositive.setVisibility(View.GONE);
                    btnNegative.setText(negativeText);
                } else if (TextUtils.isEmpty(negativeText)) {
                    btnPositive.setVisibility(View.GONE);
                    btnNegative.setText(positiveText);
                } else {
                    btnPositive.setText(positiveText);
                    btnNegative.setText(negativeText);

                    if (mButtonClickListener != null) {
                        btnPositive.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                mButtonClickListener.onClick(dialog, DownTimerDialog.BUTTON_POSITIVE);
                            }
                        });
                    }

                }

                if (mButtonClickListener != null) {
                    btnNegative.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            mButtonClickListener.onClick(dialog, DownTimerDialog.BUTTON_NEGATIVE);
                        }
                    });
                }
            }

            return dialog;

        }


    }


    public interface OnDownTimerListener {
        /**
         * 倒计时中回调 1s回调一次
         */
        void onDowningTimer(DialogInterface dialog, long millisUntilFinished);

        /**
         * 倒计时结束回调
         */
        void onDownTimerFinished(DialogInterface dialog);
    }


    /**
     * 静态内部类：倒计时
     */
    private class DialogTimer extends CountDownTimer {


        DialogTimer(long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);
        }

        @Override
        public void onTick(long millisUntilFinished) {
            Message message = Message.obtain();
            message.what = 2;
            message.obj = millisUntilFinished;
            mHandler.sendMessage(message);
        }

        @Override
        public void onFinish() {
            mHandler.sendEmptyMessage(3);
        }
    }

}
